﻿@inject ChatState _chatState
@implements IDisposable

<MudPaper Class="overflow-hidden text-field-custom pb-8 pt-4 w-100" Elevation="0" Style="background-color: var(--mud-palette-background)">
    <MudPaper Class="inner-paper mud-theme-lighten w-100 mt-0 mx-auto" Style="@BackgroundColorStyle" Elevation="3">
        <MudGrid>
            <MudItem xs="12">
                <MudTextField id="prompt-input"
                              OnKeyDown="HandleKeyDown"
                              T="string"
                              Variant="Variant.Filled"
                              @bind-Value="Message"
                              Immediate="true"
                              Class="text-field-custom mt-n5 mb-n3"
                              Placeholder="@(SelectedActionId != Guid.Empty ? ActionPromptText : ChatPromptText)"
                              Lines="1"
                              MaxLines="14"
                              AutoGrow="true"
                              FullWidth="true"
                              DisableUnderLine="true"
                              KeyDownPreventDefault="_preventDefault" />
            </MudItem>
            <MudItem xs="12" Class="d-flex justify-content-between align-items-center pa-0">
                <div class="d-flex gap-0.25 ml-4">

                    <ActionSelectorPopover CurrentValue="CurrentValueAction" ActionChanged="OnActionChanged" />

                    <MudIconButton id="prompt-input-attach-file-button" Icon="@Icons.Material.Filled.AttachFile" Color="Color.Inherit" Disabled="true" />
                    <MudIconButton id="prompt-input-mic-button" Icon="@Icons.Material.Filled.Mic" Color="Color.Inherit" Disabled="true" />
                    @if (selectedChipText.IsNotEmpty())
                    {
                        <MudChip Class="my-auto" Color="Color.Dark" OnClose="@(() => CloseChip(selectedChipText))">@selectedChipText</MudChip>
                    }
                </div>
                <div class="flex-grow-1"></div>
                    @if (IsProcessing)
                    {
                        <div class="mr-1 d-flex align-items-center justify-content-center relative" style="width: 48px; height: 48px; top: 14px;">
                            <MudProgressCircular Color="Color.Default" Size="Size.Small" Indeterminate="true" />
                        </div>
                    }
                    else
                    {
                    <MudIconButton id="prompt-input-send-button" Icon="@Icons.Material.Filled.Send" OnClick="@( () =>SendMessage(Message))" Color="Color.Info" Class="mr-4" Disabled="@IsSendButtonDisabled" />
                    }
            </MudItem>
        </MudGrid>
    </MudPaper>
</MudPaper>

<style>
    .text-field-custom .mud-input-filled {
        background-color: var(--mud-textfield-background) !important;
    }
</style>

@code
{
    [Parameter] public EventCallback<string> OnSend { get; set; }
    [CascadingParameter] private bool _IsDarkModeEnabled { get; set; }
    private string BackgroundColorStyle => $"background-color: {(_IsDarkModeEnabled ? "#2B2B34" : "#f5f5f5")}; max-width: 960px;";

    private string Message { get; set; } = string.Empty;
    private bool IsSendButtonDisabled => string.IsNullOrWhiteSpace(Message);
    private bool IsProcessing { get; set; }

    private NativeActionResponse? CurrentValueAction { get; set; }
    private Guid SelectedActionId { get; set; }

    private bool _preventDefault = false;
    private string selectedChipText = string.Empty;
    private string ActionPromptText => $"Ready to perform '{CurrentValueAction?.Name}' action? Provide your command or close the action chip to go back to chatting";
    private string ChatPromptText = "Type a message";

    protected override void OnInitialized()
    {
        _chatState.ActionIdChanged += StateHasChanged;
    }

    private async Task SendMessage(string message)
    {
        if (!IsSendButtonDisabled)
        {
            IsProcessing = true;
            Message = string.Empty;

            await OnSend.InvokeAsync(message);

            IsProcessing = false;
        }
    }

    private async Task HandleKeyDown(KeyboardEventArgs e)
    {
        if (e.Key == "Enter" && !e.ShiftKey && !IsSendButtonDisabled)
        {
            _preventDefault = true;
            var tempMessage = Message;
            await SendMessage(tempMessage);
        }

        if (e.Key == "Enter" && e.ShiftKey)
        {
        }

        _preventDefault = false;
    }

    private void OnActionChanged(NativeActionResponse action)
    {
        if (action is not null)
        {
            _chatState.SetActionId(action.Id);
            SelectedActionId = _chatState.ActionId;
            CurrentValueAction = action;
            selectedChipText = action.Name;
        }
    }

    private void CloseChip(string chipText)
    {
        CurrentValueAction = null;
        selectedChipText = string.Empty;
        _chatState.SetActionId(Guid.Empty);
        SelectedActionId = _chatState.ActionId;
    }

    public void Dispose()
    {
        _chatState.ActionIdChanged -= StateHasChanged;
    }
}
